<template>
  <div class="order-container">
    <!-- 店铺信息 -->

    <!-- 客户信息 -->
    <div class="customer-info" @click="switchAddress">
      <div class="customer-row">
        <div class="customer-avatar">
          <image
            src="https://cphimg.leyoo888.com/dev/upload/supplier/2025-05-04/1746344971744.png"
            class="avatar-img"
          >
          </image>
        </div>
        <div class="customer-data">
          <div class="customer-name">
            <span>{{ singleObj.current_address.consignee }}</span>
            <span class="mgl-40">{{ singleObj.current_address.mobile }}</span>
          </div>
          <div class="customer-address">
            {{ singleObj.current_address.address }}
          </div>
        </div>
        <div class="address-arrow">
          <text class="gui-icons arrow-icon">&#xe601;</text>
        </div>
      </div>
    </div>

    <div class="store-info">
      <div class="product-required">*</div>
      <selectSupplier
        style="width: 100%"
        v-model="singleObj.supplier_id"
        label="供应商"
        :options="singleObj.supplierList"
        placeholder="请选择供应商"
        @changeSupplier="changeSupplier"
      />
    </div>

    <!-- 商品列表 -->
    <div
      class="product-list"
      v-for="(item, index) in singleObj.detail"
      :key="index"
    >
      <!-- 商品项 - 需要添加的商品 -->
      <div class="product-item">
        <div class="product-required">*</div>
        <selectBrand
          style="width: 100%"
          v-model="item.brand_id"
          label="品牌"
          :options="item.selectOptions.brandList"
          placeholder="请选择品牌"
          :title="`请先选供应商再选择品牌`"
          @changeBrand="changeBrand(item, index)"
        />
      </div>

      <div class="product-item">
        <div class="product-required">*</div>
        <SelectGoods
          style="width: 100%"
          v-model="item.goods_id"
          label="商品"
          :options="item.selectOptions.goodsList"
          placeholder="请选择商品"
          :title="`请先选品牌再选择商品`"
          @changeGoods="changeGoods(item, index)"
          @loadMore="loadMoreGoods(index)"
        />
      </div>

      <div class="product-item">
        <CascaderGoods
          label="规格"
          required
          placeholder="请选择商品规格"
          :options="item.selectOptions.goodsSpecList"
          v-model="item.sku_id"
          @change="changeSku($event, item, index)"
          style="flex: 1"
        />
      </div>

      <div class="product-item">
        <div class="product-required">*</div>
        <div class="product-label">数量</div>
        <div class="quantity-control">
          <div class="quantity-minus" @click="decreaseQuantity(item)">-</div>
          <input
            type="number"
            class="quantity-input"
            v-model="item.quantity"
            @change="changeQuantity(item)"
          />
          <div class="quantity-plus" @click="increaseQuantity(item)">+</div>
        </div>
      </div>

      <div class="product-item no-required">
        <div class="product-label">备注</div>
        <input
          type="text"
          class="remark-input"
          placeholder="请输入备注内容"
          v-model="item.remark"
        />
      </div>

      <div class="price-info no-required">
        <div class="price-label">单价</div>
        <div class="price-value">
          ¥{{ item.price }}
          <!-- <input type="number" v-model="item.price" style="width: 200rpx" @change="changePrice(item)"></input> -->
        </div>
        <div class="total-price">总价: ¥{{ item.total_price }}</div>
      </div>

      <div class="action-buttons">
        <div class="add-button" @click="increaseAddedQuantity(index, item)">
          <gui-image
            src="https://cphimg.leyoo888.com/dev/upload/supplier/2025-05-05/1746427166764.png"
            :width="60"
            :height="60"
          />
          <text class="add-text">添加</text>
        </div>
        <div
          class="add-button"
          v-if="singleObj.detail.length > 1"
          @click="decreaseAddedQuantity(index)"
        >
          <gui-image
            src="https://cphimg.leyoo888.com/dev/upload/supplier/2025-05-05/1746427171920.png"
            :width="60"
            :height="60"
          />
          <text class="add-text">删除</text>
        </div>
      </div>
    </div>

    <!-- 底部结算栏 -->
    <div class="footer">
      <div class="total-section">
        合计: <text class="total-amount">¥{{ totalPrice }}</text>
        <text class="tax-info">(不含运费)</text>
      </div>
      <div class="submit-button" @click="debounce(submit, 800)">提交</div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from "vue";
import { onLoad, onShow, onUnload } from "@dcloudio/uni-app";
import {
  getSupplierList,
  getGoodsList,
  getGoodsSpecList,
  getBrandList,
  addSupplierOrder,
} from "@/apiShop/order";
import { supplierFormToShopId } from "@/apiShop/goods";
import { getDefaultAddressApi } from "@/apiShop/address";
import selectSupplier from "@/component/goods/selectSupplier.vue";
import selectBrand from "@/component/goods/selectBrand.vue";
import SelectGoods from "@/component/goods/selectGoods.vue";
import { bc, showToast } from "@/utils/helper";
import cloneDeep from "lodash.clonedeep";
import CascaderGoods from "@/component/goods/cascaderGoods.vue";
// 商品数量
const goodsObj = ref({
  brand_id: undefined,
  sku_id: undefined,
  goods_id: undefined,
  goods_spec_value_name: undefined,
  goods_spec_name: undefined,
  goods_value_name: undefined,
  quantity: 1,
  remark: "",
  price: 0,
  total_price: 0,
  selectOptions: {
    brandList: [],
    goodsList: [],
    goodsSpecList: [],
    goodsPage: {
      page: 1,
      limit: 99,
    },
  },
});
const singleObj = ref({
  supplier_id: undefined,
  supplierList: [],
  current_address: {
    consignee: "请点击选择地址",
    address: "",
    mobile: "",
    id: undefined,
  },
  user_remark: "",
  detail: [cloneDeep(goodsObj.value)],
});

const totalPrice = computed(() => {
  return singleObj.value.detail.reduce((total, item) => {
    return bc(`${total}+${item.total_price}`);
  }, 0);
});

// 增加数量
const increaseQuantity = (item) => {
  item.quantity += 1;
  item.total_price = bc(`${item.price}*${item.quantity}`);
};
const changeQuantity = (item) => {
  item.quantity = isNaN(Number(item.quantity)) ? 1 : Number(item.quantity);
  item.total_price = bc(`${item.price}*${item.quantity}`);
};
const changePrice = (item) => {
  item.price = Number(item.price).toFixed(2);
  item.total_price = bc(`${item.price}*${item.quantity}`);
};
// 减少数量
const decreaseQuantity = (item) => {
  if (item.quantity > 1) {
    item.quantity -= 1;
    item.total_price = bc(`${item.price}*${item.quantity}`);
  }
};

// 增加已添加商品数量
const increaseAddedQuantity = async (index, item) => {
  singleObj.value.detail.splice(index, 0, {
    brand_id: item.brand_id,
    sku_id: undefined,
    goods_id: item.goods_id,
    goods_spec_value_name: undefined,
    goods_spec_name: undefined,
    goods_value_name: undefined,
    quantity: 1,
    remark: "",
    price: 0,
    total_price: 0,
    selectOptions: {
      brandList: [],
      goodsList: [],
      goodsSpecList: [],
      goodsPage: {
        page: 1,
        limit: 99,
      },
    },
  });
  await getBrandListData(index);
  if (item.brand_id) {
    await getGoodsListData(item.brand_id, index);
  }
  if (item.goods_id) {
    await getGoodsSpecListData(item.goods_id, index);
  }
};

// 减少已添加商品数量
const decreaseAddedQuantity = (index) => {
  singleObj.value.detail.splice(index, 1);
};

const switchAddress = () => {
  uni.navigateTo({
    url: "/pagesShop/address/storeAddresslist?is_proxy=1",
  });
};
// 获取供应商列表
const getSupplierListData = async () => {
  const res = await getSupplierList({
    page: 1,
    limit: 99,
  });
  singleObj.value.supplierList = res;
};

//获取店铺的品牌
const getBrandListData = async (index) => {
  const res = await getBrandList({
    page: 1,
    limit: 99,
    supplier_info_id: singleObj.value.supplier_id,
  });
  singleObj.value.detail[index].selectOptions.brandList = res.map((item) => ({
    id: item.brand_id,
    name: item.name,
  }));
};

const loadMoreGoods = (index) => {
  singleObj.value.detail[index].selectOptions.goodsPage.limit += 99;
  getGoodsListData(singleObj.value.detail[index].brand_id, index);
};
// 获取商品列表
const getGoodsListData = async (id, index) => {
  const res = await getGoodsList({
    ...singleObj.value.detail[index].selectOptions.goodsPage,
    brand_id: id,
    supplier_info_id: singleObj.value.supplier_id,
  });
  singleObj.value.detail[index].selectOptions.goodsList = res.data.map(
    (item) => ({
      id: item.id,
      goods_name: item.goods_name,
      goods_image: item.goods_image,
      product_name: item.product_name,
      factory_price: item.factory_price,
    })
  );
  // 清空当前行sku规格列表
  singleObj.value.detail[index].selectOptions.goodsSpecList = [];
  singleObj.value.detail[index].selectOptions.sku_id = undefined;
  singleObj.value.detail[index].selectOptions.goods_id = undefined;
};
// 获取商品规格列表
const getGoodsSpecListData = async (id, index) => {
  const res = await getGoodsSpecList({
    goods_id: id,
    supplier_shop_id: supplier_shop_id.value,
    tree: 1,
  });
  singleObj.value.detail[index].selectOptions.goodsSpecList = res.sku;
};

const changeSupplier = async (item) => {
  // 清空每一个商品数据并注入品牌数据
  singleObj.value.detail.forEach(async (items, index) => {
    Object.assign(items, cloneDeep(goodsObj.value));
    await getBrandListData(index);
  });
  // 获取对应的供应商表店铺id
  await getSupplierShopId(item.id);
};

const changeBrand = (item, index) => {
  getGoodsListData(item.brand_id, index);
  Object.assign(
    item,
    cloneDeep({
      ...goodsObj.value,
      brand_id: item.brand_id,
      selectOptions: {
        brandList: item.selectOptions.brandList || [],
        goodsList: [],
        goodsSpecList: [],
        goodsPage: {
          page: 1,
          limit: 99,
        },
      },
    })
  );
};

const changeGoods = (item, index) => {
  getGoodsSpecListData(item.goods_id, index);
  Object.assign(
    item,
    cloneDeep({
      ...goodsObj.value,
      brand_id: item.brand_id,
      goods_id: item.goods_id,
      goods_spec_value_name: item.goods_spec_value_name,
      goods_spec_name: item.goods_spec_name,
      goods_value_name: item.goods_value_name,
      selectOptions: {
        brandList: item.selectOptions.brandList || [],
        goodsList: item.selectOptions.goodsList || [],
        goodsSpecList: [],
        goodsPage: {
          page: 1,
          limit: 99,
        },
      },
    })
  );
};

const changeSku = (event, item, index) => {
  item.price = event.discount_price;
  item.total_price = bc(`${event.discount_price} *${item.quantity}`);
  item.goods_spec_name = event.goods_spec_name.join("??");
  item.goods_value_name = event.goods_spec_value_name.join("??");
  let str = "";
  event.goods_spec_name.forEach((item, indexSpe) => {
    str += item + "：" + event.goods_spec_value_name[indexSpe] + " ";
  });
  item.goods_spec_value_name = str;
};

const checkSubmit = () => {
  if (!singleObj.value.current_address?.id) {
    uni.showToast({ title: "请选择收货地址", icon: "none" });
    return false;
  }
  if (!singleObj.value.supplier_id) {
    uni.showToast({ title: "请选择供应商", icon: "none" });
    return false;
  }
  return true;
};

const submit = async () => {
  if (!checkSubmit()) return;
  const res = await addSupplierOrder({
    supplier_info_id: singleObj.value.supplier_id,
    supplier_shop_id: supplier_shop_id.value, // 店铺id
    address_id: singleObj.value.current_address.id,
    user_remark: singleObj.value.user_remark || "",
    detail: singleObj.value.detail.map((item) => ({
      brand_id: item.brand_id,
      goods_id: item.goods_id,
      sku_id: item.sku_id,
      quantity: item.quantity,
      goods_spec_value_name: item.goods_spec_value_name,
      goods_spec_name: item.goods_spec_name,
      goods_value_name: item.goods_value_name,
      price: item.price,
      remark: item.remark,
    })),
  });
  uni.redirectTo({
    url: `/pages/success/success?totalPrice=${totalPrice.value}&type=supplier&id=${res}`,
  });
};
const getDefaultAddress = async () => {
  const res = await getDefaultAddressApi();
  res && (singleObj.value.current_address = res);
};
onUnload(() => {
  uni.$off("useAddress");
});
const supplier_shop_id = ref("");

const getSupplierShopId = async (id) => {
  const res = await supplierFormToShopId({
    supplier_info_id: id,
  });
  supplier_shop_id.value = res.supplier_shop_id;
};
onShow(() => {
  uni.$on("useAddress", (address) => {
    singleObj.value.current_address = address;
  });
});
onLoad(async () => {
  await getSupplierListData();
  await getDefaultAddress();
});
</script>

<style scoped>
.order-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 100rpx;
}

/* 店铺信息样式 */
.store-info {
  background-color: #fff;
  margin-top: 20rpx;
  padding: 0 30rpx;
  display: flex;
  align-items: center;
}

.store-name {
  font-size: 32rpx;
  font-weight: 500;
}

/* 客户信息样式 */
.customer-info {
  background-color: #fff;
  padding: 20rpx 30rpx;
  margin-top: 2rpx;
  border-bottom: 1px solid #eee;
}

.customer-row {
  display: flex;
  align-items: center;
}

.customer-avatar {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  overflow: hidden;
  margin-right: 20rpx;
}

.avatar-img {
  width: 100%;
  height: 100%;
}

.customer-data {
  flex: 1;
}

.customer-name {
  font-size: 30rpx;
  font-weight: 500;
  margin-bottom: 8rpx;
}

.customer-address {
  font-size: 26rpx;
  color: #666;
}

.address-arrow {
  width: 40rpx;
  text-align: right;
}

.arrow-icon {
  color: #ccc;
  font-size: 40rpx;
}

/* 商品列表样式 */
.product-list,
.added-product {
  background-color: #fff;
  margin-top: 20rpx;
  padding: 0 30rpx;
}

.product-item,
.added-header {
  display: flex;
  align-items: center;
  padding: 25rpx 0;
}

.product-required {
  color: #f56c6c;
  font-size: 28rpx;
  margin-right: 5rpx;
}

.product-label,
.added-title {
  width: 100rpx;
  font-size: 28rpx;
  color: #333;
}

.product-value,
.added-value {
  flex: 1;
  font-size: 28rpx;
  color: #999;
}

.product-arrow {
  width: 40rpx;
  text-align: right;
}

/* 数量控制样式 */
.quantity-control {
  display: flex;
  align-items: center;
}

.quantity-minus,
.quantity-plus {
  width: 60rpx;
  height: 60rpx;
  line-height: 56rpx;
  text-align: center;
  border: 1px solid #ddd;
  font-size: 36rpx;
  color: #333;
  background-color: #f7f7f7;
}

.quantity-input {
  width: 80rpx;
  height: 60rpx;
  line-height: 60rpx;
  text-align: center;
  font-size: 28rpx;
  border-top: 1px solid #ddd;
  border-bottom: 1px solid #ddd;
}

/* 备注输入框样式 */
.remark-input {
  flex: 1;
  font-size: 28rpx;
  height: 60rpx;
  border: none;
}

/* 价格信息样式 */
.price-info {
  display: flex;
  align-items: center;
  padding: 20rpx 0;
  border-bottom: 1px solid #f5f5f5;
}

.price-label {
  font-size: 28rpx;
  color: #666;
}

.price-value {
  font-size: 28rpx;
  color: #f56c6c;
  margin-left: 20rpx;
  display: flex;
  align-items: center;
  gap: 10rpx;
}

.total-price {
  margin-left: auto;
  font-size: 28rpx;
  color: #f56c6c;
}

/* 按钮样式 */
.action-buttons {
  display: flex;
  padding: 20rpx 0;
}

.add-button,
.delete-button {
  display: flex;
  align-items: center;
  height: 80rpx;
  padding: 0 30rpx;
  background-color: #eeeeee6b;
  border-radius: 4rpx;
  margin-right: 20rpx;
  gap: 10rpx;
}

.add-icon,
.delete-icon {
  font-size: 32rpx;
  margin-right: 8rpx;
}

.add-text,
.delete-text {
  font-size: 28rpx;
}

.delete-button {
  color: #f56c6c;
}

/* 底部结算栏样式 */
.footer {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 100rpx;
  display: flex;
  align-items: center;
  background-color: #fff;
  border-top: 1px solid #eee;
  z-index: 10;
}

.total-section {
  flex: 2;
  padding-left: 30rpx;
  font-size: 28rpx;
}

.total-amount {
  color: #f56c6c;
  font-weight: 500;
  font-size: 32rpx;
}

.tax-info {
  font-size: 24rpx;
  color: #999;
  margin-left: 8rpx;
}

.submit-button {
  flex: 1;
  height: 100%;
  background-color: #1989fa;
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 30rpx;
}

.mgl-40 {
  margin-left: 40rpx;
}

.no-required {
  margin-left: 16rpx;
}
</style>
